# 数据返回结果
from utils.code import StatusCodeEnum
from django.http.response import JsonResponse

class R(object):
    
    def __init__(self):
        self.code = None 
        self.errmsg = None 
        
    def to_json_response(self):
        """转换为字典对象

        Returns:
            dict: 字典对象{'code':2,'errmsg':'error'}
        """
        _ = dict()
        
        _['code'] = self.code
        _['errmsg'] = self.errmsg

        return JsonResponse(_,json_dumps_params={'ensure_ascii':False},safe=True)

    
    @staticmethod
    def ok():
        """返回成功消息

        Returns:
            R: R对象
        """
        r = R()
        r.code = StatusCodeEnum.OK.code
        r.errmsg = StatusCodeEnum.OK.errmsg
        
        return r.to_json_response()
    
    @staticmethod
    def warning(msg):
        """警告消息

        Args:
            msg (_type_): _description_

        Returns:
            _type_: _description_
        """
        r = R() 
        r.code = StatusCodeEnum.WARNING.code 
        r.errmsg = msg
        
        return r.to_json_response()
    
    @staticmethod
    def error():
        """
        返回错误响应信息
        """
        r = R() 
        r.code = StatusCodeEnum.ERROR.code 
        r.errmsg = StatusCodeEnum.ERROR.errmsg
        
        return r.to_json_response()
    
    @staticmethod 
    def server_error():
        """
        服务器响应错误信息
        """
        r = R()
        r.code = StatusCodeEnum.SERVER_ERR.code
        r.errmsg = StatusCodeEnum.SERVER_ERR.errmsg
        
        return r.to_json_response()
    
    @staticmethod
    def on_login():
        """没有登录

        Returns:
            R: R对象
        """
        r = R()
        r.code = StatusCodeEnum.NO_LOGIN_ERR.code
        r.errmsg = StatusCodeEnum.NO_LOGIN_ERR.errmsg
        
        return r.to_json_response() 
    
    @staticmethod
    def other_result(enum:StatusCodeEnum):
        """其它返回信息自定义

        Args:
            enum (StatusCodeEnum): 自定义状态枚举类
        """
        r = R()
        r.code = enum.code 
        r.errmsg = enum.errmsg
        
        return r.to_json_response()
    
    @staticmethod
    def param_error(params = []):
        
        _ = {
            'code':StatusCodeEnum.PARAM_ERROR.code,
            'errmsg':StatusCodeEnum.PARAM_ERROR.errmsg,
            'data':params
        } 
    
        return JsonResponse(_,json_dumps_params={'ensure_ascii':False},safe=True)
    
    def dict_result(self,dict):
        """返回数据信息

        Args:
            dict (dict): 返回的数据. Defaults to None.
        """
        _ = {
            'code':StatusCodeEnum.OK.code,
            'errmsg':StatusCodeEnum.OK.errmsg,
            'data':dict
        } 
        
        return JsonResponse(_,json_dumps_params={'ensure_ascii':False},safe=True)
    
    
